package serverproject.service;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Collection;
import java.util.logging.Logger;

import javolution.util.FastList;
import serverproject.Server;
import serverproject.model.Account;
import serverproject.model.Connection;

public class ConnectionService
{
	private static Collection<Connection>	connectedList	= new FastList<Connection>().shared();			// 멀티쓰레드환경에서의 안정성을위해 shared를 붙여
																											// threadsafe한 자료구조
																											// 생성
	private static Logger					logger			= Logger.getLogger("ConnectionService.class");

	public static final ConnectionService getInstance()
	{
		return SingletonHolder.instance;
	}

	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder
	{
		protected static final ConnectionService	instance	= new ConnectionService();
	}

	public void addConnectedList(Socket socket, PrintWriter writer, Account account)
	{
		/**
		 * 테스트용 로그 리스트가 정상적으로 추가,삭제 되는지 확인
		 */
		if (Server.useTestLog)
		{
			for (Connection connection : connectedList)
			{
				logger.info("Ip : " + connection.getSocket().getInetAddress());
			}
		}
		connectedList.add(new Connection(socket, writer, account));
	}

	public Collection<Connection> getConnectionList()
	{
		return connectedList;
	}

	/**
	 * 
	 * @param socket
	 */
	public void removeConnectedListBySocket(Socket socket)
	{
		for (Connection connection : connectedList)
		{
			if (connection.getSocket() == socket)
			{
				connectedList.remove(connection);
				break;
			}
		}

		/**
		 * 테스트용 로그 리스트가 정상적으로 추가,삭제 되는지 확인
		 */
		if (Server.useTestLog)
		{
			for (Connection connection : connectedList)
			{
				logger.info("Ip : " + connection.getSocket().getInetAddress());
			}
		}
	}

}
